package com.zuoban.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @BelongsProject: zuoban-boot
 * @BelongsPackage: com.zuoban.util
 * @Author: zxy
 * @CreateTime: 2022-10-10  10:59
 */
/**
 * jwt工具类
 */
public class JwtUtil {

    @Value("${jwt.sign}")
    private String sign;

    public String createToken(Map<String, String> claims) {
        JWTCreator.Builder builder = JWT.create();
        // 添加荷载
        claims.forEach(builder::withClaim);
        // 设置过期时间  半个月过期
        builder.withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 3600 * 15 * 24));
        return builder.sign(Algorithm.HMAC256(this.sign));
    }

    public Boolean verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
            return true;
        } catch (JWTVerificationException | IllegalArgumentException e) {
            return false;
        }
    }


    public DecodedJWT getClaims(String token) {
        try {
            return JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
        } catch (JWTVerificationException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}
